import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


class Message3 {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message3{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageServlet3 extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private DataSource  dataSource = new MysqlDataSource();

    @Override
    public void init() throws ServletException {    // 实例化servlet对象时会调用 init方法
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("cjc123456");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 读取前端发来的数据,将数据保存到服务器
        Message3 message = objectMapper.readValue(req.getInputStream(), Message3.class);
        System.out.println("请求中的数据: " + message.toString());

        // 2. 将数据保存到数据库
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 3. 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write("ok");
    }

    private void save(Message3 message) throws SQLException {
        // 1. 与数据库建立连接
        Connection connection = dataSource.getConnection();

        // 2. 构建 sql
        String sql = "insert into message values(?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,message.from);
        statement.setString(2,message.to);
        statement.setString(3,message.message);

        // 3. 执行 sql
        statement.executeUpdate();

        // 4. 关闭资源
        statement.close();
        connection.close();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 将数据库中的数据放到 messageList中
        List<Message3> messageList = null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 2. 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }

    private List<Message3> load() throws SQLException {
        List<Message3> messageList = new ArrayList<>();

        // 1. 与数据库建立连接
        Connection connection = dataSource.getConnection();

        // 2. 构造 sql
        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 3. 执行 sql
        ResultSet resultSet = statement.executeQuery();

        // 4. 遍历结果集合，将每条数据加入到 messageList 中
        while(resultSet.next()) {
            Message3 message3 = new Message3();
            String from = resultSet.getString("from");
            String to = resultSet.getString("to");
            String message = resultSet.getString("message");
            message3.from = from;
            message3.to = to;
            message3.message = message;
            messageList.add(message3);
        }

        // 5. 关闭资源并返回结果
        resultSet.close();
        statement.close();
        connection.close();
        return messageList;
    }
}
